//
//  HMNewFeatureCollectionViewController.swift
//  我的微博
//
//  Created by 杨庆 on 15/10/17.
//  Copyright © 2015年 双元班. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class HMNewFeatureCollectionViewController: UICollectionViewController {
    /// 返回的界面的数量
    private let imageCount = 4
    /// 布局属性
    private var layout = HMFlowLayOut()
    init(){
        //重写之后还是不行,报警需要调用指定的构造函数;
        super.init(collectionViewLayout:layout)
    }

    required init?(coder aDecoder: NSCoder) {
    // 1.fatalError("init(coder:) has not been implemented")//这个是本类禁用用 sb 开发,--纯代码的开发,考虑的因素少,风险小;
    // 2.而第二种的方式是: 本类允许用 sb 来开发,有些公司是混合的开发! 需要考虑的因素有很多,都需要测试才能完成;
        super.init(coder: aDecoder)
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    //MARK:-UIcollectionViewDataSoucre(数据源的方法);
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
        cell.imageIndex = indexPath.item
        cell.backgroundColor = UIColor.whiteColor()
        return cell
    }
    /// 完成之后的话再显示 cell---indexPath 是之前的消失的cell 的 indexpath
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        //获取当前显示的indexpath 
        let path = collectionView.indexPathsForVisibleItems().last!
        //判断是否是 最后的一个indexpath
        if path.item == imageCount - 1{
            //播放动画
            let cell  = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
            cell.startButtonAnimate()
        }
    }
}
/// 新特性的 cell
class NewFeatureCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        prepareUI()
    }
    //不能进行定义的 私有的属性,就是不能再来访问了
    func clickStratButton(){
        NSNotificationCenter.defaultCenter().postNotificationName(HMRootViewControllerSwitchNotification, object: true)
    }
    //图像的索引,,私有的属性 在同一个文件中是可以进行的访问的
    private var imageIndex: Int = 0 {
        didSet{
        let image1 = UIImage(named: "new_feature_\(imageIndex + 1)")
        iconView.image = image1
        startButton.hidden = true
        }
    }
    //设置按钮的动画(弹力的动画)
    private func startButtonAnimate() {
        startButton.hidden = false
        //动画没有结束的时候,不允许用户的交互;
        startButton.userInteractionEnabled = false
        /// 缩放的比例 为 0,0 的话 就是表示的是 变小为零,到后面再通过动画进行回复来原型了
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        UIView.animateWithDuration(1.2, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                //恢复默认的初始的动画
                self.startButton.transform = CGAffineTransformIdentity
            }) { (_ ) -> Void in
                self.startButton.userInteractionEnabled = true
        }
    }
    
    //准备UI
    private func prepareUI(){
        //添加控件,都建议是添加到contentView 上
//        iconView.ff_Fill(contentView)
        contentView.addSubview(iconView)
        contentView.addSubview(startButton)
        //自动布局
        iconView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subView" : iconView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subView" : iconView]))
//        startButton.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))
        startButton.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint( NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute:  NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        contentView.addConstraint( NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute:  NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))

    }
    //MARK:-懒加载控件;
    private lazy var iconView = UIImageView()
    private lazy var startButton : UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_Highlighted"), forState: UIControlState.Highlighted)
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        btn.sizeToFit()
        //添加点击的事件
        btn.addTarget(self , action: "clickStratButton", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
}
/// 自定义的流水布局
private class HMFlowLayOut: UICollectionViewFlowLayout{
    //准备布局的属性
    private override func prepareLayout() {
        itemSize = (collectionView?.bounds.size)!
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    }
}

